<template>
  <ContentBase>
    <div class="row justify-content-center">
      <div class="col-3">
        <!-- .prevent 阻止表单提交默认行为 ，默认的提交行为是跳转页面 ，会一闪而过-->
        <form @submit.prevent="register">
          <div class="mb-3">
            <label for="username" class="form-label">用户名</label>
            <input v-model="username" type="username" class="form-control" id="username">
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">密码</label>
            <input v-model="password" type="password" class="form-control" id="password">
          </div>
          <div class="mb-3">
            <label for="password_confirm" class="form-label">确认密码</label>
            <input v-model="password_confirm" type="password" class="form-control" id="password_confirm">
          </div>
          <div class="error-message">{{error_message}}</div>
          <button type="submit" class="btn btn-primary">注册</button>
        </form>
      </div>
    </div>
  </ContentBase>
</template>

<script>
// @ is an alias to /src
import ContentBase from '../components/ContentBase.vue';
import {ref} from 'vue';
import $ from 'jquery';
import {useStore} from 'vuex';
import router from "@/router/index.js";
export default {
  name: 'RegisterView',
  components: {
    ContentBase,
  },
  setup() {
    let username=ref("");
    let password=ref("");
    let error_message=ref("");
    let password_confirm=ref("");
    const store=useStore();
    const register=()=>{
      error_message.value=""; //每次点击注册按钮，先把错误信息清空
      $.ajax({
        url:"https://app165.acapp.acwing.com.cn/myspace/user/",
        type:"POST",
        data:{
          username:username.value,
          password:password.value,
          password_confirm:password_confirm.value,
        },
        success(resp){
          if(resp.result==="success"){ 
            store.dispatch("login",{ //注册成功后直接登录
              username:username.value,
              password:password.value,
              success(){
                console.log("success");
                router.push({name:'userlist'});//登录成功跳转到用户列表页面
              },
              error(){
                error_message.value="系统异常，请稍后重试";
              }
            });
          }else{
            error_message.value=resp.result; //显示错误信息
          }
        }
      })
    };
    return {
      username,
      password,
      password_confirm,
      error_message,
      register,
    }
  }
}
</script>

<style scoped>
button{
  width: 100%;
}
.error-message {
  color: red;
}
</style>
